/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/10
 */
import type { RouteLocationNormalized } from 'vue-router'
import type { anyObj } from '@/types'
import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'

export type IMenu = {
    title: string
    icon?: string
    path: string
    name: string
    params?: anyObj
    query?: anyObj
    // 是否为外部地址
    externalLinks: boolean
    children?: IMenu[]
}

export const useMenu = defineStore('menu', () => {
    // 通过后台获取到的导航数据
    const menu = ref<IMenu[]>([])

    const navTabs = reactive<{
        lists: IMenu[]
        activeIndex: number
        activeRoute?: IMenu
    }>({
        // 导航tab
        lists: [],
        // 活动菜单索引
        activeIndex: 0,
        // 活动菜单路由
        activeRoute: undefined,
    })

    const setMenu = (m: IMenu[]) => {
        menu.value.length = 0
        menu.value = m
    }

    /**
     * 添加nav tab
     * @param route
     */
    const addRouteNav = (route: IMenu | RouteLocationNormalized) => {
        // 如果已经存在路由则更新路由即可
        for (const routeKey of navTabs.lists) {
            if (routeKey.path === route.path) {
                routeKey.params = route.params ?? {}
                routeKey.query = route.query ?? {}
                return
            }
        }
        const currentRoute = findMenu(menu.value, route.path)
        if (!currentRoute) return
        currentRoute.params = route.params ?? {}
        currentRoute.query = route.query ?? {}

        navTabs.lists.push(Object.assign({}, currentRoute))
    }

    const closeTab = (route: IMenu) => {
        for (const key in navTabs.lists) {
            if (navTabs.lists[key].path === route.path) {
                navTabs.lists.splice(key as any, 1)
                break
            }
        }
    }

    const setActiveRoute = (route: IMenu | RouteLocationNormalized) => {
        const currentRoute = findMenu(menu.value, route.path)
        if (!currentRoute) return
        const index = navTabs.lists.findIndex((item) => {
            return item.path === route.path
        })
        if (index === -1) return
        navTabs.activeRoute = currentRoute
        navTabs.activeIndex = index
    }

    return {
        menu,
        navTabs,
        closeTab,
        setMenu,
        addRouteNav,
        setActiveRoute,
    }
})

const findMenu: any = (menus: IMenu[], path: string) => {
    for (const key in menus) {
        if (menus[key].path == path) {
            return menus[key]
        } else if (menus[key].children) {
            const done = findMenu(menus[key].children as IMenu[], path)
            if (done) return done
        }
    }
}
